/* Copyright */
/*******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2014 Tsunagi-BPM
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *******************************************************************************/
 /* Copyright End */
 
package tsunagi.common.util;

import java.net.URLEncoder;
import java.util.ArrayList;

import tsunagi.common.Lang;
import tsunagi.common.SystemException;

public class Parameters extends ArrayList<Parameter> {
	private static final long serialVersionUID = 1L;
	
	private boolean urlEncode = true;
	private String enc = "utf-8";
	
	public Parameters(boolean enc) {
		super();
		this.setUrlEncode(enc);
	}
	
	public Parameters(String enc) {
		super();
		this.setUrlEncode(true);
		this.setEnc(enc);
	}
	
	public String getEnc() {
		return enc;
	}

	public void setEnc(String enc) {
		this.enc = enc;
	}

	public void addParam(String key, String value) {
		Parameter param = new Parameter();
		param.setKey(key);
		param.setValue(value);
		this.add(param);
	}
	
	public String toString() {
		StringBuffer result = new StringBuffer();
		for(Parameter param: this) {
			String val = param.getValue();
			if (this.isUrlEncode()) {
				try {
					val = URLEncoder.encode(val, this.getEnc());
				}catch(Exception e){
					throw new SystemException(e);
				}
			}
			result.append(param.getKey()+ Lang.STRING_EQUAL + param.getValue()+Lang.STRING_AMPERSAND);
		}
		if (result.length() > 0)
			result.deleteCharAt(result.length()-1); // remove the last '&'
		return result.toString();
	}
	
	public String formatUrlParams() {
		this.setUrlEncode(true); // make sure...
		return Lang.STRING_QUESTION + this.toString();
	}
	
	public boolean isUrlEncode() {
		return urlEncode;
	}

	public void setUrlEncode(boolean urlEncode) {
		this.urlEncode = urlEncode;
	}
}
